//
//  GYDHomeWBTableViewCell.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/27.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import SnapKit
import ReactiveCocoa
import SDWebImage

class GYDHomeWBTableViewCell: UITableViewCell {
    
    private var bottomView : UIView?//底部灰色
    
    private var timeLabel : UILabel? //创建时间
    private var contentLabel : UILabel? //正文
    private var vipImageView : UIImageView? //vip图标
    private var nameLabel : UILabel? //名字
    private var iconImageView : UIImageView? //头像
    private var verifiedImageView : UIImageView? //认证图标
    private var sourceLabel : UILabel? //来源
    private var collectionView : UICollectionView? //图片
    private var layout : UICollectionViewFlowLayout? //布局
    private var collectionViewWidth : Constraint?//图片宽度约束
    private var collectionViewTop : Constraint?//图片顶部约束
    private var itemSize : CGSize?
    private var bgView : UIView? //承载转发微博配图和文字和原创微博的配图
    private var forwardTextLabel : UILabel?//转发微博内容
    
    var shareButton : UIButton?//分享按钮
    var commentsButton : UIButton?//评论按钮
    var hitsButton : UIButton?//点赞按钮
    var downButton : UIButton?//更多按钮
    
    private var wbModel : GYDWBModel?
    
    
    
    //配图点击信号
    lazy var imageSignal : RACSubject = {
        return RACSubject()
    }()
    
    

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = UIColor.whiteColor()
        self.selectionStyle = UITableViewCellSelectionStyle.None
        createSubViews()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createSubViews() {
        
        //头像
        let iconImageView = UIImageView()
        iconImageView.image = UIImage(named: "avatar_default_big")
        iconImageView.layer.cornerRadius = 20
        iconImageView.layer.masksToBounds = true
        self.iconImageView = iconImageView
        contentView.addSubview(iconImageView)
        iconImageView.snp_makeConstraints { (make) in
            make.left.top.equalTo(10)
            make.width.height.equalTo(40)
        }
        //认证
        let verifiedImageView = UIImageView()
        verifiedImageView.layer.cornerRadius = 7
        verifiedImageView.layer.masksToBounds = true
        self.verifiedImageView = verifiedImageView
        contentView.addSubview(verifiedImageView)
        verifiedImageView.snp_makeConstraints { (make) in
            make.width.height.equalTo(14)
            make.right.equalTo(iconImageView.snp_right)
            make.bottom.equalTo(iconImageView.snp_bottom)
        }
        //名字
        let nameLabel = UILabel()
        nameLabel.textColor = RGB(242, g: 98, b: 31)
        nameLabel.font = UIFont.systemFontOfSize(17)
        self.nameLabel = nameLabel
        contentView.addSubview(nameLabel)
        nameLabel.snp_makeConstraints { (make) in
            make.left.equalTo(iconImageView.snp_right).offset(10)
            make.top.equalTo(iconImageView.snp_top)
            make.height.equalTo(20)
        }
        //vip
        let vipImageView = UIImageView()
        self.vipImageView = vipImageView
        contentView.addSubview(vipImageView)
        vipImageView.snp_makeConstraints { (make) in
            make.left.equalTo(nameLabel.snp_right).offset(2)
            make.width.height.equalTo(14)
            make.centerY.equalTo(nameLabel.snp_centerY)
        }
        //时间
        let timeLabel = UILabel()
        timeLabel.textColor = TEXTBASECOLOR
        timeLabel.font = UIFont.systemFontOfSize(11)
        self.timeLabel = timeLabel
        contentView.addSubview(timeLabel)
        timeLabel.snp_makeConstraints { (make) in
            make.left.equalTo(nameLabel.snp_left)
            make.height.equalTo(20)
            make.top.equalTo(nameLabel.snp_bottom)
        }
        //来源
        let sourceLabel = UILabel()
        contentView.addSubview(sourceLabel)
        sourceLabel.textColor = BLUECOLOR
        sourceLabel.font = UIFont.systemFontOfSize(11)
        self.sourceLabel = sourceLabel
        sourceLabel.snp_makeConstraints { (make) in
            make.left.equalTo(timeLabel.snp_right).offset(3)
            make.top.equalTo(timeLabel.snp_top)
            make.height.equalTo(timeLabel.snp_height)
        }
        
        let downButton = UIButton(type: UIButtonType.Custom)
        self.downButton = downButton
        downButton.setImage(UIImage(named: "timeline_icon_more"), forState: UIControlState.Normal)
        contentView.addSubview(downButton)
        downButton.snp_makeConstraints { (make) in
            make.top.equalTo(0)
            make.right.equalTo(0)
            make.width.equalTo(35)
            make.height.equalTo(35)
        }
        
        
        //内容
        let contentLabel = UILabel()
        contentLabel.numberOfLines = 7
        contentLabel.textColor = RGB(40, g: 40, b: 40)
        contentLabel.font = UIFont.systemFontOfSize(16)
        self.contentLabel = contentLabel
        contentView.addSubview(contentLabel)
        contentLabel.snp_makeConstraints { (make) in
            make.left.equalTo(iconImageView.snp_left)
            make.right.equalTo(-10)
            make.top.equalTo(iconImageView.snp_bottom).offset(5)
        }
        
        //第一条横线
        let lineView2 = UIView()
        lineView2.backgroundColor = RGB(220, g: 220, b: 220)
        contentView.addSubview(lineView2)
        lineView2.snp_makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.height.equalTo(0.5)
            make.bottom.equalTo(-45)
        }
        
        
        //承载视图
        let bgView = UIView()
        self.bgView = bgView
        bgView.backgroundColor = RGB(250, g: 250, b: 250)
        contentView.addSubview(bgView)
        bgView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(contentLabel.snp_bottom).offset(0)
            make.bottom.equalTo(lineView2.snp_top).offset(-5)
        }
        
        let forwardTextLabel = UILabel()
        forwardTextLabel.numberOfLines = 7
        forwardTextLabel.textColor = RGB(120, g: 120, b: 120)
        forwardTextLabel.font = UIFont.systemFontOfSize(16)
        self.forwardTextLabel = forwardTextLabel
        bgView.addSubview(forwardTextLabel)
        forwardTextLabel.snp_makeConstraints { (make) in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(5)
        }
        
        
        
        //内容图片
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        self.layout = layout
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        self.collectionView = collectionView
        self.collectionView?.scrollEnabled = false
        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.bounces = false
        bgView.addSubview(collectionView)
        collectionView.snp_makeConstraints { (make) in
            make.left.equalTo(10)
            self.collectionViewWidth = make.width.equalTo(40).constraint
            self.collectionViewTop = make.top.equalTo(forwardTextLabel.snp_bottom).offset(5).constraint
            make.bottom.equalTo(-5)
        }
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "collectionCellId")
        
        
        
        
        //分享按钮
        let shareButton = UIButton(type: UIButtonType.Custom)
        shareButton.setTitleColor(RGB(140, g: 140, b: 140), forState: UIControlState.Normal)
        shareButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        shareButton.setTitle(" 分享", forState: UIControlState.Normal)
        shareButton.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        self.shareButton = shareButton
        contentView.addSubview(shareButton)
        shareButton.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.width.equalTo(GYDWindowWidth/3.0)
            make.height.equalTo(35)
            make.top.equalTo(lineView2.snp_bottom)
        }
        
        //评论按钮
        let commentsButton = UIButton(type: UIButtonType.Custom)
        commentsButton.setTitleColor(RGB(140, g: 140, b: 140), forState: UIControlState.Normal)
        commentsButton.setTitle(" 评论", forState: UIControlState.Normal)
        commentsButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        commentsButton.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        self.commentsButton = commentsButton
        contentView.addSubview(commentsButton)
        commentsButton.snp_makeConstraints { (make) in
            make.left.equalTo(shareButton.snp_right)
            make.width.equalTo(shareButton.snp_width)
            make.height.equalTo(shareButton.snp_height)
            make.top.equalTo(shareButton.snp_top)
        }
        //点赞按钮
        let hitsButton = UIButton(type: UIButtonType.Custom)
        hitsButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        hitsButton.setTitleColor(RGB(140, g: 140, b: 140), forState: UIControlState.Normal)
        hitsButton.setTitle(" 赞", forState: UIControlState.Normal)
        hitsButton.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal)
        self.hitsButton = hitsButton
        contentView.addSubview(hitsButton)
        hitsButton.snp_makeConstraints { (make) in
            make.left.equalTo(commentsButton.snp_right)
            make.width.equalTo(shareButton.snp_width)
            make.height.equalTo(shareButton.snp_height)
            make.top.equalTo(shareButton.snp_top)
        }
        //竖线1
        let lineView3 = UIView()
        lineView3.backgroundColor = RGB(220, g: 220, b: 220)
        contentView.addSubview(lineView3)
        lineView3.snp_makeConstraints { (make) in
            make.left.equalTo(shareButton.snp_right)
            make.width.equalTo(0.5)
            make.top.equalTo(shareButton.snp_top).offset(8)
            make.bottom.equalTo(shareButton.snp_bottom).offset(-8)
        }
        //竖线2
        let lineView4 = UIView()
        lineView4.backgroundColor = RGB(220, g: 220, b: 220)
        contentView.addSubview(lineView4)
        lineView4.snp_makeConstraints { (make) in
            make.left.equalTo(commentsButton.snp_right)
            make.width.equalTo(0.5)
            make.top.equalTo(shareButton.snp_top).offset(8)
            make.bottom.equalTo(shareButton.snp_bottom).offset(-8)
        }
        
        //最下面横线
        let lineView = UIView()
        lineView.backgroundColor = RGB(200, g: 200, b: 200)
        contentView.addSubview(lineView)
        lineView.snp_makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.height.equalTo(0.5)
            make.top.equalTo(shareButton.snp_bottom).offset(-0.5)
        }
        //灰色
        let bottomView = UIView()
        self.bottomView = bottomView
        bottomView.backgroundColor = BASECOLOR
        contentView.addSubview(bottomView)
        bottomView.snp_makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(lineView.snp_bottom)
            make.bottom.equalTo(0)
        }
    }
    
}

//#MARK: -业务处理
extension GYDHomeWBTableViewCell {
    func updateDataWithWBModel(wbModel: GYDWBModel)  {
       self.wbModel = wbModel
        //头像
        if wbModel.user?.profile_image_url != nil {
            let userUrl = NSURL(string: (wbModel.user?.profile_image_url)!)
            iconImageView?.sd_setImageWithURL(userUrl, placeholderImage: UIImage(named: "avatar_default_big"))
        }
        self.contentLabel?.text = wbModel.text
        
        //名字
        nameLabel?.text = wbModel.user?.screen_name
        //vip图标和认证图标
        setUpVipAndVerifiedIcon(wbModel)
        
        //时间 来源
        setUpCreateTimeAndSouce(wbModel)
        
        //设置按钮
        setUpButtons(wbModel)
        //更新配图
        updateCollectionView(wbModel)
        
    }
    
    private func updateCollectionView(wbModel: GYDWBModel) {
        let model : GYDWBModel
        if wbModel.retweeted_status == nil {
            model = wbModel
        }else {
            model = wbModel.retweeted_status!
        }
        
        if wbModel.retweeted_status == nil {
            self.forwardTextLabel?.text = nil
            self.bgView?.backgroundColor = UIColor.whiteColor()
            self.collectionViewTop?.updateOffset(0)
        }else {
            self.bgView?.backgroundColor = RGB(250, g: 250, b: 250)
            var forwoardName = wbModel.retweeted_status?.user?.screen_name ?? ""
            if forwoardName.characters.count > 0 {
                forwoardName = "@" + forwoardName + ":"
            }
            let forwoardText = wbModel.retweeted_status?.text ?? ""
            let str = forwoardName + forwoardText
            if str.characters.count > 0 {
                self.forwardTextLabel?.text = str
                self.collectionViewTop?.updateOffset(5)
            }else {
                self.forwardTextLabel?.text = nil
                self.collectionViewTop?.updateOffset(0)
            }
        }
        
        let (itemSize, collectionViewSize) = GYDHomeWBTableViewCell.calculateSize(model)
        if collectionViewSize.width != 0 {
            self.layout?.itemSize = itemSize
            self.collectionViewWidth?.updateOffset(collectionViewSize.width)
        }else {
            self.collectionViewWidth?.updateOffset(0)
        }
        collectionView?.reloadData()
    }
    
    private func setUpVipAndVerifiedIcon(wbModel: GYDWBModel) {
        //认证图标
        if wbModel.user?.verified == false {
            verifiedImageView?.hidden = true
        }else {
            var verImageName : String?
            if let type = wbModel.user?.verified_type {
                switch type {
                case 0:
                    verImageName = "avatar_vip"
                    break
                case 2,3,5:
                    verImageName = "avatar_enterprise_vip"
                    break
                case 220:
                    verImageName = "avatar_grassroot"
                    break
                default:
                    verImageName = nil
                }
            }
            if verImageName != nil {
                verifiedImageView?.hidden = false
                verifiedImageView?.image = UIImage(named: verImageName!)
            }
        }
        
        //会员图标
        vipImageView?.image = UIImage(named: "common_icon_membership")
        
        if wbModel.user?.mbrank >= 1 && wbModel.user?.mbrank <= 6 {
            if let brank = wbModel.user?.mbrank {
                vipImageView?.image = UIImage(named:"common_icon_membership_level\(brank)")
                nameLabel?.textColor = RGB(242, g: 98, b: 31)
            }
        }else {
            vipImageView?.image = nil
            nameLabel?.textColor = NAVTINTCOLOR
        }
    }
    private func setUpCreateTimeAndSouce(wbModel: GYDWBModel) {
        //时间
        if let timeStr = wbModel.created_at {
            //格式化时间
            let dataFormatter = NSDateFormatter()
            dataFormatter.dateFormat = "EE MM dd HH:mm:ss Z yyyy"
            //指定时区
            dataFormatter.locale = NSLocale(localeIdentifier: "en")
            //格式化
            let createDate = dataFormatter.dateFromString(timeStr)
            
            
            //创建日历类
            let calender = NSCalendar.currentCalendar()
            //是否是今天
            if calender.isDateInToday(createDate!) {
                //比较
                let inerval = Int(NSDate().timeIntervalSinceDate(createDate!))
                if inerval < 60 {
                    timeLabel?.text = "刚刚"
                }else if inerval < 60*60 {
                    timeLabel?.text = "\(inerval/60)分钟前"
                }else if inerval < 60*60*24 {
                    timeLabel?.text = "\(inerval/(60*60))小时前"
                }
            }else if calender.isDateInYesterday(createDate!) {
                dataFormatter.dateFormat = "昨天 " + "HH:mm"
                timeLabel?.text = dataFormatter.stringFromDate(createDate!)
            }else {
                let comps = calender.components(NSCalendarUnit.Year, fromDate: createDate!, toDate: NSDate(), options: NSCalendarOptions(rawValue:0))
                if comps.year >= 1 {
                    dataFormatter.dateFormat = "yyyy-MM-dd " + "HH:mm"
                    timeLabel?.text = dataFormatter.stringFromDate(createDate!)
                }else {
                    dataFormatter.dateFormat = "MM-dd " + "HH:mm"
                    timeLabel?.text = dataFormatter.stringFromDate(createDate!)
                }
            }
  
        }
        
        // 来源
        if let source : NSString = wbModel.source where source != "" {
            let startIndex = source.rangeOfString(">").location + 1
            let length = source.rangeOfString("<",options: NSStringCompareOptions.BackwardsSearch).location - startIndex
            let rest = source.substringWithRange(NSMakeRange(startIndex, length))
            let sourceAtt = NSMutableAttributedString(string: String(format: "来自%@",rest))
            sourceAtt.setAttributes([NSForegroundColorAttributeName:TEXTBASECOLOR], range: NSMakeRange(0, 2))
            sourceLabel?.attributedText = sourceAtt
        }
        
        
        
    }
    
    private func setUpButtons(wbModel: GYDWBModel) {
        if wbModel.reposts_count == 0 {
            self.shareButton!.setTitle(" 分享", forState: UIControlState.Normal)
        }else {
            self.shareButton!.setTitle(" \(wbModel.reposts_count)", forState: UIControlState.Normal)
        }
        
        if wbModel.comments_count == 0 {
            self.commentsButton!.setTitle(" 评论", forState: UIControlState.Normal)
        }else {
            self.commentsButton!.setTitle(" \(wbModel.comments_count)", forState: UIControlState.Normal)
        }
        
        if wbModel.attitudes_count == 0 {
            self.hitsButton!.setTitle(" 赞", forState: UIControlState.Normal)
        }else {
            self.hitsButton!.setTitle(" \(wbModel.attitudes_count)", forState: UIControlState.Normal)
        }
        
    }
    
    
    
    static private func calculateSize(wbModel: GYDWBModel) -> (CGSize,CGSize) {
        
        let imageCount = wbModel.pic_urls?.count ?? 0
        //没有配图 cell = zero collection = zero
        if imageCount == 0 {
            return (CGSizeZero,CGSizeZero)
        }
        //一张配图 cell = 图片的狂傲 collection= cell
        if imageCount == 1 {
            let key = wbModel.pic_urls?.first!["thumbnail_pic"]
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size,image.size)
        }
        let imageWidth : CGFloat = (GYDWindowWidth - 8 - 20) / 3.0
        let imageHeight = imageWidth
        let margin : CGFloat = 4.0
        
        //四张 cell =
        if imageCount == 4 {
            return (CGSize(width: imageWidth, height: imageHeight),CGSize(width: 2*imageWidth+margin, height: 2*imageWidth+margin))
        }
        let row = (imageCount - 1) / 3 + 1
        
        return (CGSize(width: imageWidth, height: imageHeight),CGSize(width: 3*imageWidth+2*margin, height: CGFloat(row)*imageHeight + CGFloat(row-1)*margin))
    }
    
    //MARK: -计算行高
    static func calculateRowHeight(wbModel: GYDWBModel) -> CGFloat {
        let model : GYDWBModel
        if wbModel.retweeted_status == nil {
            model = wbModel
        }else {
            model = wbModel.retweeted_status!
        }
        let collectionViewSize = GYDHomeWBTableViewCell.calculateSize(model).1
        var height : CGFloat = 0.0
        if let text = wbModel.text {
            height = text.sizeWithString(UIFont.systemFontOfSize(16), size: CGSizeMake(GYDWindowWidth - 20, 145)).height
        }
        var forwoardHeight : CGFloat = 0.0
        var forwoardName = wbModel.retweeted_status?.user?.screen_name ?? ""
        if forwoardName.characters.count > 0 {
            forwoardName = "@" + forwoardName + ":"
        }
        let forwoardText = wbModel.retweeted_status?.text ?? ""
        let str = forwoardName + forwoardText
        if str.characters.count > 0 {
            forwoardHeight = str.sizeWithString(UIFont.systemFontOfSize(16), size: CGSizeMake(GYDWindowWidth - 20, 145)).height
        }
        
        return 10 + 40 + 5 + height + 5 + forwoardHeight + 5 + collectionViewSize.height + 10 + 35 + 10
    }
}



//#MARK: -配图代理
//#MARK: - UICollectionViewDataSource   UICollectionViewDelegate
extension GYDHomeWBTableViewCell:UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let model = self.wbModel else {
            return 0
        }
        let nowmodel : GYDWBModel
        if model.retweeted_status == nil {
            nowmodel = model
        }else {
            nowmodel = model.retweeted_status!
        }
        return nowmodel.pic_urls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCellId", forIndexPath: indexPath)
        
        
        let nowmodel : GYDWBModel
        if wbModel!.retweeted_status == nil {
            nowmodel = wbModel!
        }else {
            nowmodel = wbModel!.retweeted_status!
        }
        let url = nowmodel.pic_urls![indexPath.item]["thumbnail_pic"]
        let view = cell.contentView.viewWithTag(800)
        var imageView : UIImageView?
        if view == nil {
            imageView = UIImageView()
            imageView!.contentMode = UIViewContentMode.ScaleAspectFill
            imageView!.clipsToBounds = true
            cell.contentView.addSubview(imageView!)
            imageView!.snp_makeConstraints(closure: { (make) in
                make.left.equalTo(0)
                make.bottom.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(0)
            })
            imageView!.tag = 800
        }else {
            imageView = view as? UIImageView
        }
        imageView?.sd_setImageWithURL(NSURL(string: url!))
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let nowmodel : GYDWBModel
        if wbModel!.retweeted_status == nil {
            nowmodel = wbModel!
        }else {
            nowmodel = wbModel!.retweeted_status!
        }
        var frameDic : [Int:NSValue] = [Int:NSValue]()
        var imageSize : [Int:NSValue] = [Int:NSValue]()
        for cell in collectionView.visibleCells() {
            let cellFrame = collectionView.convertRect(cell.frame, toView: UIApplication.sharedApplication().keyWindow)
            frameDic[(collectionView.indexPathForCell(cell)?.item)!] = NSValue(CGRect:cellFrame)
            let imageView = cell.contentView.viewWithTag(800) as! UIImageView
            let size = imageView.image?.size
            imageSize[(collectionView.indexPathForCell(cell)?.item)!] = NSValue(CGSize:size!)
        }
        var imageUrl : [String] = [String]()
        for urldic in nowmodel.pic_urls! {
            imageUrl.append(urldic["thumbnail_pic"]!)
        }
        
        
        let picDic : [String : NSObject] = [SELECTEDINDEX:indexPath.item,ALLIMAGEURL:imageUrl,CELLFRAMEDIC:frameDic,CELLIMAGESIZE:imageSize]
        self.imageSignal.sendNext(picDic)
    }
    
}



